package com.lagouedu.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author:
 * @Description:自定义类加载器
 * @Date: Create in 10:50 上午 2020/3/26
 */
public class SimpleClassLoader extends ClassLoader {

  @Override
  public Class<?> findClass(String name) throws ClassNotFoundException {
    //去拿到生成好的class文件
    File classFile = new File(name + ".class");
    //将这个class文件手动加载进入jvm中
    if (classFile.exists()) {
      FileInputStream in = null;
      ByteArrayOutputStream out = null;
      try {
        in = new FileInputStream(classFile);
        out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
          out.write(buffer, 0, len);
        }
        //这里是jdk底层的方法
        return defineClass(getClassPath(name), out.toByteArray(), 0, out.size());
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (null != out) {
          try {
            out.close();
          } catch (IOException e) {
            e.printStackTrace();
          } finally {
            if (null != in) {
              try {
                in.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }
      }
    }
    return null;
  }

  private String getClassPath(String path) {
    int index = path.indexOf("com");
    String substring = path.substring(index);
    substring = substring.replace("/", ".");
    return substring;
  }
}
